<?php

namespace App\Services;

use App\Models\BlogArticle;
use App\Models\BlogCategory;
use App\Models\BlogMusic;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Mail\Markdown;

class ArticleService extends BaseService
{
    /**
     * 获取文章列表
     * @param int $page
     * @param int $limit
     * @param array $where
     * @param array|string[] $columns
     * @return array|mixed
     */
    public function getArticleList(int $page, int $limit, array $where, array $columns = ['id', 'title', 'author', 'brief', 'comment_num', 'read_num', 'created_at', 'updated_at'])
    {
        $articles = BlogArticle::query()
            ->where($where)
            ->orderByDesc('id')
            ->paginate($limit, $columns, 'page', $page);
        return $this->successPaginate($articles);
    }


    /**
     * 获取文章详情
     * @param int $articleId
     * @param array|string[] $columns
     * @return BlogArticle|BlogArticle[]|Builder|Builder[]|Collection|Model|null
     */
    public function getArticleDetail(int $articleId, array $columns = ['*'])
    {
        $article = BlogArticle::query()->find($articleId, $columns);
        $article['content'] = Markdown::parse($article['content']);
        visits(BlogArticle::class, $articleId)->increment();
        return $article;
    }

    /**
     * 获取所有文章
     * @param array|string[] $columns
     * @return BlogArticle[]|Builder[]|Collection
     */
    public function getArticles(array $columns = ['id', 'title', 'author', 'brief', 'comment_num', 'read_num', 'created_at', 'updated_at'])
    {
        return BlogArticle::query()->orderByDesc('id')->get($columns);
    }

    // 右侧栏数据
    public function getSidebarData()
    {
        $articles = $this->getArticles();
        $result = [];
        // 右侧栏 - 最新文章
        $result['lastArticles'] = collect($articles)->take(3);
        // 右侧栏 - 归档
        $result['archiveDates'] = collect($articles)->groupBy('date')->keys();
        // 右侧栏 - 分类
        $result['categories'] = BlogCategory::query()->with('article:id,category_id,title')
            ->orderBy('sort')
            ->get(['id', 'name', 'sort']);
        return $result;
    }

    /**
     * 获取音乐列表
     * @return BlogMusic[]|Collection
     */
    public function getMusicList()
    {
        return BlogMusic::get();
    }

}
